package pojo1

import "fmt"

type GreaterHeap struct {
	Array       []Customer
	HeapSize    int
	IndexMap    map[Customer]int
	CompareFunc func(Customer, Customer) bool
}

func NewGreaterHeap(compareFunc func(Customer, Customer) bool) *GreaterHeap {

	return &GreaterHeap{Array: make([]Customer, 100), HeapSize: 0, IndexMap: make(map[Customer]int), CompareFunc: compareFunc}
}

func (g *GreaterHeap) swap(i, j int) {
	c1 := g.Array[i]
	c2 := g.Array[j]
	g.IndexMap[c1], g.IndexMap[c2] = j, i
	g.Array[i], g.Array[j] = c2, c1
}
func (g *GreaterHeap) HeapUp(index int) {

	for g.CompareFunc(g.Array[index], g.Array[(index-1)/2]) {
		g.swap(index, (index-1)/2)
		index = (index - 1) / 2
	}

}
func (g *GreaterHeap) HeapDown(index int) {
	leftChild := index*2 + 1
	for leftChild < g.HeapSize {
		temp := leftChild
		if leftChild+1 < g.HeapSize && g.CompareFunc(g.Array[leftChild+1], g.Array[leftChild]) {
			temp = leftChild + 1
		}

		if g.CompareFunc(g.Array[temp], g.Array[index]) {
			temp = index
		}

		if temp == index {
			break
		}
		g.swap(temp, index)
		index = temp
		leftChild = index*2 + 1
	}

}

func (g *GreaterHeap) Resign(c *Customer) {

	index := g.IndexMap[*c]
	g.HeapUp(index)
	g.HeapDown(index)
}

// 去除指定的Customer对象
func (g *GreaterHeap) Remove(c *Customer) {
	i := g.IndexMap[*c]
	g.swap(i, g.HeapSize-1)
	g.HeapSize--
	delete(g.IndexMap, g.Array[g.HeapSize])
}

// 弹出最后的Customer对象
func (g *GreaterHeap) Poll() {
	g.swap(0, g.HeapSize-1)
	g.HeapSize--
	g.HeapDown(0)
}

func (g *GreaterHeap) Push(c *Customer) {
	g.Array[g.HeapSize] = *c
	g.IndexMap[*c] = g.HeapSize
	g.HeapUp(g.HeapSize)
	g.HeapSize++
}
func (g *GreaterHeap) Print() {

	for i := 0; i < g.HeapSize; i++ {
		fmt.Println(g.Array[i], "   ", i)
	}
	fmt.Println()
	fmt.Println()
	for index, value := range g.IndexMap {
		fmt.Println(index, "   ", value)

	}
}
